import json

from captcha.helpers import captcha_image_url
from captcha.models import CaptchaStore
from django.contrib.auth import authenticate, login
from django.http import HttpResponse, Http404
from django.shortcuts import render
from .forms import UserLoginFrom


# Create your views here.

def index(request):
    if request.method == 'POST':
        user_login_from = UserLoginFrom(request.POST)
        if user_login_from.is_valid():
            username = user_login_from.cleaned_data['username']
            password = user_login_from.cleaned_data['password']
            user = authenticate(username=username, password=password)
            if user:
                login(request, user)
                return HttpResponse('{}'.format(user.username))
            else:
                return render(request, 'login.html', {'msg': '账号有问题，请联系管理员', 'user_login_from': user_login_from})
        else:
            if user_login_from.errors:
                return render(request, 'login.html', { 'user_login_from': user_login_from})
            else:
                return render(request, 'login.html', {'msg': '账号或密码错误', 'user_login_from': user_login_from})
    else:
        user_login_from = UserLoginFrom()
        return render(request, 'login.html', {'user_login_from': user_login_from})


# 只是源码介绍不用写入自己的代码中
def captcha_refresh(request):
    """  Return json with new captcha for ajax refresh request """
    if not request.is_ajax():  # 只接受ajax提交
        raise Http404

    new_key = CaptchaStore.generate_key()
    to_json_response = {
        'key': new_key,
        'image_url': captcha_image_url(new_key),
    }
    return HttpResponse(json.dumps(to_json_response), content_type='application/json')
